<template>
  <span v-if="invisible"></span>

  <div v-else-if="widget === 'image_url'">
    <!-- todo: {{ [field.type, fname, widget] }} -->

    <WImage
      :type="type"
      :value_readonly="value_readonly"
      :editable="editable"
      :data-info="dataInfo"
      :view-info="{ ...viewInfo, node }"
      @on-change="onchange"
    />
  </div>

  <div v-else-if="widget_todo">todo: {{ [field.type, fname, widget] }}</div>

  <div v-else-if="type === 'cell'">
    <van-form ref="refForm">
      <template v-if="readonly || !editable">
        <van-field readonly :value="value_display">
          <template #label>
            <OLabel :data-info="dataInfo" :view-info="viewInfo" />
          </template>
        </van-field>
      </template>

      <template v-else>
        <van-field
          v-model="value2"
          :rules="[{ required, message: '不能为空', trigger: 'onChange' }]"
          @blur="handleBlur"
        >
          <template #label>
            {{ required ? '*' : '' }}
            <OLabel :data-info="dataInfo" :view-info="viewInfo" />
          </template>
        </van-field>
      </template>
    </van-form>
  </div>

  <span v-else-if="readonly || !editable">
    <!-- {{ [field.type, fname] }} -->
    {{ value_display }}
    <!-- {{ type }} -->
  </span>
  <div v-else>edit: {{ [field.type, fname] }}</div>
</template>

<script>
import OFMixin from './OFMixin'
import OLabel from '../OLabel.vue'
import WImage from './WImage.vue'

export default {
  name: 'FChar',
  components: { OLabel, WImage },
  mixins: [OFMixin],
  props: {},
  data() {
    return {
      value2: ''
    }
  },
  computed: {
    value_readonly() {
      return this.record[this.fname] || ''
    },

    value() {
      return this.value_edit || ''
    },

    widget_todo() {
      const done = []
      return done.includes(this.widget) ? '' : this.widget
    }
  },

  watch: {
    value: {
      // eslint-disable-next-line no-unused-vars
      handler: function (newVal, oldval) {
        // console.log('watch, value:', this.fname, newVal, oldval)
        this.initValue(newVal)
      },
      deep: true,
      immediate: true
    }
  },

  created() {},

  mounted() {},

  methods: {
    initValue(value) {
      this.value2 = value
    },

    async handleBlur() {
      console.log('handleBlur', this.value2)
      try {
        await this.$refs.refForm.validate()
        this.onchange(this.value2)
      } catch (e) {
        this.onchange(this.value2, { local_onchange: 1 })
      }
    }
  }
}
</script>

<style type="text/css"></style>
